import React, { Component } from 'react'
import ReactDOM from 'react-dom'

export default class App extends Component {
  state = {
    username: 'xxx',
    content: '',
    frame: 'vue',
    sex: 'male',
    checkbox: ['apple']
  }
  HandleChange = (e) => {
    let v
    // 如果操作的是checkbox
    if(e.target.type === 'checkbox'){
      // 找一下额。target.value 在不在this.state.checkbox中
      const index = this.state.checkbox.indexOf(e.target.value)
      if (index !== -1) {
        // 说明在：曾经有，那么就删除掉
        const copyCheckbox = [...this.state.checkbox]
        // 根据索引，从index开始删除，删一个
        copyCheckbox.splice(index, 1)
        // 把删完的结果给变量v
        v = copyCheckbox
      } else {
        // 说明没有，没有就是点击添加(期望选中)
        // 把最终结果给v
        v = [...this.state.checkbox, e.target.value]
      }
      this.setState({
        [e.target.name] : v
      })
    } else {
      v = e.target.value
    }
    this.setState({
      [e.target.name]: v
    })
   
  }

  render () {
    const { username, content, frame, sex, checkbox } = this.state
    return (
      <ul>
        <li>
          <label hemlfor='username'>用户名</label>
          <input id='username' name='username' type='text' value={username} onChange={this.HandleChange}></input>
        </li>
        <li>
          <label hemlfor='content'>其他信息</label>
          <textarea id='content' name='content' type='text' value={content} onChange={this.HandleChange}
            cols='30'
            rows='10'
          ></textarea>
        </li>
        <li>
          <label hemlfor='frame'>框架</label>
          <select id='frame' name='frame' value={frame} onChange={this.HandleChange}>
            <option value='react'>React</option>
            <option value='vue'>Vue</option>
            <option value='angular'>Angular</option>
          </select>
        </li>
        <li>
          <input type='radio' name='sex' id='male' value='male' checked={sex === 'male'} onChange={this.HandleChange}></input>
          <label hemlfor='male'>男</label>

          <input type='radio' name='sex' id='female' value='female' checked={sex === 'female'} onChange={this.HandleChange}></input>
          <label hemlfor='female'>女</label>

          <input type='radio' name='sex' id='unkonw' value='unkonw' checked={sex === 'unkonw'} onChange={this.HandleChange}></input>
          <label hemlfor='unkonw'>未知</label>
        </li>

        <li>
          {/* 当 checkbox 数组里面包含 'apple' 应该选中 */}
          <input type='checkbox' name='checkbox' id='apple' value='apple' checked={checkbox.includes('apple')} onChange={this.HandleChange}></input>
          <label hemlfor='apple'>Apple</label>
          <input type='checkbox' name='checkbox' id='orange' value='orange' checked={checkbox.includes('orange')} onChange={this.HandleChange}></input>
          <label hemlfor='orange'>Apple</label>
        </li>
      </ul>
    )
  }
}

ReactDOM.render(<App />, document.querySelector('#react'))